package com.ano.service;

import com.ano.dao.UserDAO;
import com.ano.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.Date;

@Transactional
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserDAO userDAO;

    @Override
    public User login(User user) {
        User loginUser = userDAO.findByName(user.getUsername());
        if(loginUser==null){
            //如果为空说明用户名不存在
            throw new RuntimeException("用户名不存在！！！");
        }else if(!loginUser.getPassword().equals(user.getPassword())){
            //如果密码不同
            throw new RuntimeException("密码错误！！！");
        }
        return loginUser;
    }

    @Override
    public void register(User user) {

        //先去表中查看是否存在这个名字
        User findUser = userDAO.findByName(user.getUsername());
        if(findUser==null){
            //如果为空说明名字不存在
            //按学号查找
            findUser = userDAO.findByStuId(user.getStuid());
            if(findUser==null){
                //学号未被注册账号未被注册
                String id = UUID.randomUUID().toString();
                user.setId(id);
                Date loguptime = new Date();
                user.setLoguptime(loguptime);
                userDAO.save(user);

            } else{
                //如果学号相同，则不能创建
                throw new RuntimeException("该学号已被注册！！！");
            }

        }else{
            //如果user1能查到，说明用户名已经存在，不能重复
            throw new RuntimeException("用户名已存在！！！");
        }

    }

    @Override
    public void modify(User user) {
        //没什么需要处理的直接存就是了
        userDAO.update(user);
    }

    /**
     * 删除user
     * @param id
     */
    @Override
    public void delete(String id) {
        userDAO.delete(id);
    }

    /**
     * 通过id查找user
     * @param id
     * @return
     */
    @Override
    public User findById(String id) {
        User user = userDAO.findById(id);
        if(user==null){
            throw new RuntimeException("id不存在");
        }
        return user;
    }

    /**
     * 通过username查找user
     * @param username
     * @return
     */
    @Override
    public User findByName(String username) {
        User user = userDAO.findByName(username);
        if(user==null){
            throw new RuntimeException("username不存在");
        }
        return user;
    }
}
